/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-06-04
 * Time: 17:11
 */
public class HashBucket2<K, V> {
    public double LoadFactor = 0.75;//负载因子

    static class Node<K, V> {
        public K key;
        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.val = val;
            this.key = key;
        }
    }

    public Node<K, V>[] array;

    public HashBucket2() {
        this.array = (Node<K, V>[]) new Node[10];
    }

    private int size;

    //计算当前负载因子
    private double getLoadFactor() {
        return size * 1.0 / array.length;
    }

    private void resize() {
        Node<K, V>[] newArr = (Node<K, V>[]) new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node<K, V> cur = array[i];
            while (cur != null) {
                int newIndex = (cur.key.hashCode()) % newArr.length;
                Node<K, V> cN = cur.next;
                cur.next = newArr[newIndex];
                newArr[newIndex] = cur;
                cur = cN;
            }
            array = newArr;
        }


    }

    //插入
    public void put(K key, V val) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.val = val;
                return;//更新val
            }
            cur = cur.next;
        }
        Node<K, V> newNode = new Node<>(key, val);
        newNode.next = array[index];
        array[index] = newNode;
        size++;
        if (getLoadFactor() >= LoadFactor) {
            resize();//扩容
        }
    }

    //根据key,返回val
    public V get(K key) {
        int index = (key.hashCode()) % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }

}
